package lastfm;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import musictrackrecommendation.DatabaseDataset;
import musictrackrecommendation.ExperimentParameters;

import randomwalk.Submatrix;

public class LastfmTrackTrackSubmatrix extends Submatrix {

	public static final String TRACK1_ID = "track1_id";
	public static final String TRACK2_ID = "track2_id";
	
	public LastfmTrackTrackSubmatrix() throws ClassNotFoundException,
			SQLException {
		super();
	}

	public LastfmTrackTrackSubmatrix(int[] rowIds, int[] columnIds,
			double[] values, double[] transponedValues) {
		super(rowIds, columnIds, values, transponedValues);
	}

	@Override
	public String getTableName() {
		return LastfmDataset.TRACK_TRACK_TABLE_NAME;
	}

	@Override
	public String getRowFieldName() {
		return TRACK1_ID;
	}

	@Override
	public String getColumnFieldName() {
		return TRACK2_ID;
	}

	@Override
	public String getOrderFieldName() {
		return LastfmDataset.ID_ATTRIBUTE;
		//return TRACK1_ID;
	}

	@Override
	public int getSubmatrixSize() {
		ExperimentParameters parameters = ExperimentParameters.getInstance();		
		LastfmDataset datasetProperties = (LastfmDataset) parameters.getDatasetProperties();
		return datasetProperties.getTrackTrackCount();
	}

	@Override
	public double[] getSubmatrixValues(int[] columnIds) {
		double[] similarity = new double[columnIds.length];
        try {
        	ExperimentParameters parameters = ExperimentParameters.getInstance();
    		DatabaseDataset datasetDatabase = parameters.getDatasetDatabase();
    		
    		Class.forName(datasetDatabase.getJdbcDriverName()); 

	        Connection con =
	                DriverManager.getConnection(
	                		datasetDatabase.getJdbcConnectionUrl(),
	                		datasetDatabase.getDatabaseUser(), 
	                		datasetDatabase.getPassword());

            Statement stmt = con.createStatement();
            String query = "SELECT similarity FROM " + getTableName() + " ORDER BY "+ getOrderFieldName();;
            ResultSet rs = stmt.executeQuery(query);

            int i = 0;
            while (rs.next()) {
            	similarity[i] = rs.getDouble(1);
            	i++;
            }
            con.close();
            stmt.close();
        } 
        catch (ClassNotFoundException e) {
			System.out.println("Cannot register JDBC driver");
			e.getMessage();
		} catch (SQLException e) {
			System.out.println("Cannot retrieve data from database");
			e.getMessage();
		}
        return similarity;
    }
}
